package com.cxc.zk.distributed.demo;

import org.I0Itec.zkclient.ZkClient;
import java.util.concurrent.CountDownLatch;

public abstract class  ZkAbstractLock implements Lock {

    // 集群连接地址
    protected String CONNECTION = "127.0.0.1:2181";
    // zk客户端连接
    protected ZkClient zkClient = new ZkClient(CONNECTION);
    // path路径
    protected String lockPath = "/path";
    protected CountDownLatch countDownLatch = new CountDownLatch(1);

    public void getLock(){
        if (tryLock()){
            System.out.println("####获取锁成功######");
        } else {
            waitLock();
            getLock();
        }
    }
    // 获取锁
    protected abstract void waitLock();
    //释放锁
    protected abstract boolean tryLock();
    public void unLock() {
        if (zkClient != null) {
            zkClient.delete(lockPath);
            zkClient.close();
            System.out.println("#######释放锁#########");
        }
    }
}
